//
//  UIECGReview3x4Controler.m
//  vhStressECG
//
//  Created by jia yu on 2021/12/3.
//

#import "UIECGReview3x4Controler.h"

@interface UIECGReview3x4Controler(){
    UIImage *clearImage;
    UIImage *bgImage;
}
@end

@implementation UIECGReview3x4Controler
@synthesize handler;
@synthesize pixPermm;

-(void)leadClick:(id)sender{
    UIButton *button = (UIButton *)sender;
//    NSLog(@"Click Lead:%@",[vhECGTools leadName:button.tag]);
//    NSNumber *lead_index = [NSNumber numberWithInteger:button.tag];
    if (handler){
        handler(button.tag);
    }
    return;
}

-(id)initWithFrame:(CGRect)frame{
    self = [super initWithFrame:frame];
    if (self){
        pixPermm = 6.2f;
        self.backgroundColor = [UIColor clearColor];
        UIView *v = [[UIView alloc] initWithFrame:CGRectMake(0.f, 0.f, 2.f, 2.f)];
        v.backgroundColor = [UIColor clearColor];
        UIGraphicsBeginImageContext(CGSizeMake(2.f, 2.f));
        [v.layer renderInContext:UIGraphicsGetCurrentContext()];
        clearImage = UIGraphicsGetImageFromCurrentImageContext();
        v.backgroundColor = [UIColor colorWithRed:0.5f green:0.5f blue:0.5f alpha:0.3f];
        [v.layer renderInContext:UIGraphicsGetCurrentContext()];
        bgImage = UIGraphicsGetImageFromCurrentImageContext();
        UIGraphicsEndImageContext();
        
        clearImage = [clearImage stretchableImageWithLeftCapWidth:1 topCapHeight:1];
        bgImage = [bgImage stretchableImageWithLeftCapWidth:1 topCapHeight:1];

        [self reloadButtons];
    }
    return self;
}

-(void)reloadButtons{
    for (UIView *v in self.subviews){
        if ([v isKindOfClass:[UIButton class]]){
            [v removeFromSuperview];
        }
    }
    
    float buttonWidth = (self.frame.size.width - 7.5f * pixPermm)/4.f;
    float height = self.frame.size.height/4.33f;
    for (int i=0;i<12;i++){
        float middle = (i%3 + 0.66) * height;
        float x = 7.5f * pixPermm + buttonWidth * (i/3);
        UIButton *button = [[UIButton alloc] initWithFrame:CGRectMake(x, middle-height/2.f, buttonWidth, height)];
        button.backgroundColor = [UIColor clearColor];
        [button setBackgroundImage:clearImage forState:UIControlStateNormal];
        [button setBackgroundImage:bgImage forState:UIControlStateHighlighted];
        button.tag = i;
        [button addTarget:self action:@selector(leadClick:) forControlEvents:UIControlEventTouchUpInside];
        [self addSubview:button];
    }
}

-(void)setPixPermm:(float)_pixPermm{
    pixPermm = _pixPermm;
    [self reloadButtons];
}
@end
